package interview.thread;

/**
 * 中断线程demo
 *
 * @Author: cctv
 * @Date: 2019/5/20 10:26
 */
public class InterruptDemo {
    public static void main(String[] args) throws InterruptedException {
        Runnable interruptTask = new Runnable() {
            @Override
            public void run() {
                int i = 0;
                Thread t = Thread.currentThread();
// 加上注释看阻塞状态的处理 去掉注释看工作状态的处理
//                try {
                    while (!t.isInterrupted()) {
//                        Thread.sleep(100);
                        i++;
                        System.out.println(t.getName() + "(" + t.getState() + ") loop " + i);
                    }
                    System.out.println(t.getName() + "(" + t.getState() + ") Thread isInterrupted. loop is" + i);
//                } catch (InterruptedException e) {
//                    System.out.println(t.getName() + "(" + t.getState() + ") catch InterruptedException. loop is " + i);
//                }
            }
        };
        Thread t1 = new Thread(interruptTask, "t1");
        System.out.println(t1.getName() + "(" + t1.getState() + ") is new");

        t1.start();
        System.out.println(t1.getName() + "(" + t1.getState() + ") is started");

        Thread.sleep(300);
        t1.interrupt();
        System.out.println(t1.getName() + "(" + t1.getState() + ") is interrupted");

        Thread.sleep(300);
        System.out.println(t1.getName() + "(" + t1.getState() + ") is terminated");
    }
}
